package dp05.leertaak1.server.protocol;

import java.util.Stack;

import dp05.leertaak1.command.definitions.Command;
import dp05.leertaak1.command.definitions.RevertableCommand;
import dp05.leertaak1.command.implementations.Insert;
import dp05.leertaak1.server.ClientHandler.Action;
import dp05.leertaak1.server.Server;

public class ProtocolDbUnavailable extends Protocol
{
    private Stack<RevertableCommand> commandQueue = new Stack<RevertableCommand>();
    private Stack<RevertableCommand> undoStack = new Stack<RevertableCommand>();

    @Override
    public String createAndExecuteCommand(Action currentAction, String[] parameters)
    {
        String returnMessage = null;
        Command currentCommand = null;

        switch (currentAction)
        {
            case INSERT:
                if (parameters.length > 1)
                {
                    int value = 0;
                    try
                    {
                        value = Integer.parseInt(parameters[1]);
                    } catch (NumberFormatException nfe)
                    {
                        return "Please enter a real number";
                    }
                    currentCommand = new Insert(Server.dao, value);
                    commandQueue.add((RevertableCommand) currentCommand);
                    returnMessage = String.format("%d added tot the actionlist", value);
                }
                break;
            case UNDO:
                RevertableCommand undo = commandQueue.pop();
                returnMessage = "Command '" + undo.toString() + "' is undone";
                undoStack.push(undo);
                break;
            case REDO:
                RevertableCommand redo = undoStack.pop();
                returnMessage = "Command '" + redo.toString() + "' is redone";
                commandQueue.push(redo);
                break;
            case COMMIT:
                for (RevertableCommand command : commandQueue)
                {
                    Server.addCommandToQueue(command);
                }
                returnMessage = "Changes comitted: they will be processed as soon as the database is available";
                break;
            case CLOSE:
                returnMessage = "Connection closed. Changes discarded";
                break;
            default:
                returnMessage = "Invalid command";
                break;
        }
        return returnMessage;
    }

}
